//
//  BaseModel.m
//  StoneMason
//
//  Created by iOS1 on 16/12/5.
//  Copyright © 2016年 iOS1. All rights reserved.
//

#import "BaseModel.h"
#import <objc/runtime.h>

@interface BaseModel() {}
@end

@implementation BaseModel

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    
}

-(void)encodeWithCoder:(NSCoder *)aCoder
{
    NSDictionary *dic = [self getAllPropertiesAndVaules];
    for (NSString *key in [dic allKeys]) {
        id value = dic[key];
        [aCoder encodeObject:value forKey:key];
    }
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    if (self=[super init]) {
        NSArray *propsArr = [self getAllPropertiesName];
        for (NSString *propertyName in propsArr) {
            id property = [coder decodeObjectForKey:propertyName];
            [self setValue:property forKey:propertyName];
        }
    }
    return self;
}

-(NSString *)description
{
    
    return [[self getAllPropertiesAndVaules] description];
}

-(NSArray *)getAllPropertiesName
{
    NSMutableArray *props = @[].mutableCopy;
    unsigned int outCount , i;
    objc_property_t *properties =class_copyPropertyList([self class], &outCount);
    for (i = 0; i<outCount; i++)
    {
        objc_property_t property = properties[i];
        const char* char_f =property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:char_f];
        [props addObject:propertyName];
    }
    free(properties);
    return [NSArray arrayWithArray:props];
}

- (NSDictionary *)getAllPropertiesAndVaules
{
    NSMutableDictionary *props = [NSMutableDictionary dictionary];
    unsigned int outCount, i;
    objc_property_t *properties =class_copyPropertyList([self class], &outCount);
    for (i = 0; i<outCount; i++)
    {
        objc_property_t property = properties[i];
        const char* char_f =property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:char_f];
        id propertyValue = [self valueForKey:(NSString *)propertyName];
        if (propertyValue) [props setObject:propertyValue forKey:propertyName];
    }
    free(properties);
    return [NSDictionary dictionaryWithDictionary:props];
}

@end
